package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService{
    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//         1. 根据用户名找到用户
        User userInDb=userService.findUserByUsername(username);
//         2. 没有则返回null
        if (userInDb==null){
            return null;
        }


        List<GrantedAuthority> list = new ArrayList<>();
//         4. 有用户则认证授权
        Set<Role> roles = userInDb.getRoles();
        if (roles!=null && roles.size()>0){
            for (Role role:roles){
//            授予角色
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
//            授予权限
                Set<Permission> permissions = role.getPermissions();
                if (permissions!=null && permissions.size()>0){
                    for (Permission permission: permissions){
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }

//         4. 把密码和用户名字和角色和授权交给SpringSecurity
        return new org.springframework.security.core.userdetails.User(username,userInDb.getPassword(),list);
    }
}
